package com.studerb.view.headers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.AbstractApplicationContext;

import com.studerb.events.listener.AbstractTaskListener;
import com.studerb.model.Post;
import com.studerb.service.interfaces.IHeaderService;
import com.studerb.util.Util;

public class HeadersTable extends JTable implements ApplicationContextAware {
	private final static String DOWNLOAD_BODY = "Download Body";
	private final static String DOWNLOAD_ARTICLE = "Download Article";
	private final static String POST_PROPERTIES = "Post Properties";

	private Post selectedPost = null;
	private static final Logger logger = Logger.getLogger(HeadersTable.class);
	private final HeadersTableModel headersTableModel;
	private AbstractApplicationContext appContext;
	@Autowired IHeaderService headerService;

	public HeadersTable(HeadersTableModel tableModel) {
		super(tableModel);
		headersTableModel = tableModel;
	}

	public void init() {
		setAutoCreateRowSorter(true);
		setFillsViewportHeight(true);
		setToolTipText(null);
		selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		selectionModel.addListSelectionListener(new HeadersTableListSelectionEL());
		addMouseListener(new HeadersTableMouseListener());
	}

	public void setApplicationContext(ApplicationContext applicationContext) {
		appContext = (AbstractApplicationContext) applicationContext;
	}

	class DownloadArticleTL extends AbstractTaskListener {
		private final Post post;

		DownloadArticleTL(Post post) {
			this.post = post;
		}

		@Override public void finished(com.studerb.events.TaskEvent event) {}
	}

	class HeadersTableListSelectionEL implements ListSelectionListener {

		@Override public void valueChanged(ListSelectionEvent e) {
			if (e.getValueIsAdjusting()) {
				return;
			}
			int selectedRowIndex = getSelectedRow();
			if (selectedRowIndex != -1) {
				int convertedIndex = convertRowIndexToModel(selectedRowIndex);
				Post post = headersTableModel.getPost(convertedIndex);
				selectedPost = post;
				// logger.debug("Set selected header to: " +
				// header.getMessageId());
			}
		}
	}

	class HeadersTableMouseListener extends MouseAdapter {
		@Override public void mouseClicked(MouseEvent e) {
			if (SwingUtilities.isRightMouseButton(e)) {
				JTable table = (JTable) e.getSource();
				int row = table.rowAtPoint(e.getPoint());
				changeSelection(row, 0, false, false);
				// logger.debug("Got right click at row: " + row);
				JPopupMenu popupMenu = new JPopupMenu();
				JMenuItem menuItemBody = new JMenuItem(DOWNLOAD_BODY);
				JMenuItem menuItemArticle = new JMenuItem(DOWNLOAD_ARTICLE);
				JMenuItem menuItemPostProperties = new JMenuItem(POST_PROPERTIES);
				popupMenu.add(menuItemBody);
				popupMenu.add(menuItemArticle);
				popupMenu.add(menuItemPostProperties);
				RightClickAL rightClickAL = new RightClickAL();
				menuItemBody.addActionListener(rightClickAL);
				menuItemArticle.addActionListener(rightClickAL);
				menuItemPostProperties.addActionListener(rightClickAL);
				popupMenu.show(table, e.getX(), e.getY() - 10);
			}
		}
	}

	class RightClickAL implements ActionListener {
		@Override public void actionPerformed(ActionEvent e) {
			if (e.getActionCommand() == DOWNLOAD_ARTICLE) {
				Post post = selectedPost;
				if (post != null) {
					DownloadArticleTL listener = new DownloadArticleTL(post);
					headerService.downloadArticle(post, listener);
				}
			}
			else if (e.getActionCommand() == DOWNLOAD_BODY) {
				Post post = selectedPost;
				if (post != null) {
					DownloadArticleTL listener = new DownloadArticleTL(post);
					headerService.downloadBody(post, listener);
				}
			}
			else if (e.getActionCommand() == POST_PROPERTIES) {
				Post post = selectedPost;
				if (post != null) {
					logger.debug("Getting properties for post: " + post.toString());
					JFrame mainFrame = Util.getSwingApplication().getMainFrame();
					JDialog postPropDlg = (JDialog) appContext.getBean("postPropertiesDlg", new Object[] { mainFrame, post });
					postPropDlg.setLocationRelativeTo(mainFrame);
					postPropDlg.setVisible(true);
				}
			}

		}
	}

}
